//
//  FinderHomeViewController.m
//  ForYourBeauty
//
//  Created by Kelly xu on 2019/5/22.
//  Copyright © 2019 changrenTech. All rights reserved.
//

#import "FinderHomeViewController.h"
#import "FiderListCell.h"
#import "FinderDetailViewController.h"
#import "FinderViewModel.h"
#import "BannerCell.h"
@interface FinderHomeViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,BannerCellDelegate>{
    
}
@property(nonatomic,weak)IBOutlet UITextField *searchText;
@property(nonatomic,weak)IBOutlet UIImageView *searchBg;
@property(nonatomic,weak)IBOutlet UIImageView *listBg;
@property(nonatomic,weak)IBOutlet UIView *bgView;
@property(nonatomic,strong)UIScrollView *categoryList;
@property(nonatomic,strong)UITableView *mainTableView;
@property(nonatomic,strong)FinderViewModel *finderViewModel;
//分类列表
@property(nonatomic,strong)NSMutableArray *bannerList;
@property(nonatomic,strong)NSMutableArray *catList;
@property(nonatomic,strong)NSMutableArray *finderList;
@property(nonatomic,assign)BOOL isRequest;
@property(nonatomic,assign)NSInteger selectCatIndex;
@property(nonatomic,strong)NSString *keyWord;
@end

@implementation FinderHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectCatIndex = 0;
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden = YES;
    [self.listBg setImage:[[UIImage imageNamed:@"cornerBg"] stretchableImageWithLeftCapWidth:[UIImage imageNamed:@"cornerBg"].size.width/2 topCapHeight:[UIImage imageNamed:@"cornerBg"].size.height/2]];
    self.bgView.layer.cornerRadius = 10;
    self.bgView.backgroundColor = [UIColor clearColor];
    self.bgView.clipsToBounds = YES;
    [self createElement];
    [self createUI];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (!self.isRequest) {
        [self.finderViewModel fetchBannerList:^(NSMutableArray * _Nonnull bannerList) {
            [self.bannerList removeAllObjects];
            [self.bannerList addObjectsFromArray:bannerList];
            [self.mainTableView reloadData];
        }];
        [self.finderViewModel fetchFinderCatWithCmp:^(NSMutableArray * _Nonnull catList) {
            [self.catList addObjectsFromArray:catList];
            [self reloadCategoryScrollSubViews];
            [self requestData];
        }];
        self.isRequest = YES;
    }
}
-(void)requestData{
    if ([self.catList count]>self.selectCatIndex) {
        SysDicModel *model = [self.catList objectAtIndex:self.selectCatIndex];
        [self.finderViewModel fetchFinderList:model.dictCode keyWord:self.keyWord cmp:^(NSMutableArray * _Nonnull finderList) {
            [self.finderList removeAllObjects];
            [self.finderList addObjectsFromArray:finderList];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mainTableView reloadData];
            });
        }];
    }
}
-(void)createUI{
    [self.bgView addSubview:self.mainTableView];
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgView);
        make.right.equalTo(self.bgView);
        make.top.equalTo(self.bgView);
        make.bottom.equalTo(self.bgView);
    }];
    self.searchText.delegate = self;
    self.searchBg.layer.cornerRadius = 22;
    self.searchBg.clipsToBounds = YES;
}
-(void)createElement{
    [self.view addSubview:self.categoryList];
    [self.categoryList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.top.equalTo(self.searchText.mas_bottom).offset(20);
        make.height.mas_equalTo(28);
    }];
}
-(void)reloadCategoryScrollSubViews{
    for (UIView *view in self.categoryList.subviews) {
        [view removeFromSuperview];
    }
    CGFloat elementWidth = (DEVICE_WIDTH-40)/4;
    for (int i=0; i<[self.catList count]; i++) {
        SysDicModel *model = [self.catList objectAtIndex:i];
        SMBButton *button = [[SMBButton alloc]initWithFrame:CGRectMake(elementWidth*i, 0, elementWidth, 28) title:model.dictName pressed:^(UIButton *button) {
            for (UIView *view in self.categoryList.subviews) {
                if (view.tag>=9000) {
                    UIButton *button1 = (UIButton*)view;
                    [button1.titleLabel setFont:[UIFont systemFontOfSize:13]];
                }
            }
            [button.titleLabel setFont:[UIFont systemFontOfSize:20]];
            self.selectCatIndex = button.tag - 9000;
            [self requestData];
        }];
        button.tag = 9000+i;
        if (i==0) {
            [button.titleLabel setFont:[UIFont systemFontOfSize:20]];
        }else{
            [button.titleLabel setFont:[UIFont systemFontOfSize:13]];
        }
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.categoryList addSubview:button];
    }
    [self.categoryList setContentSize:CGSizeMake(elementWidth*[self.catList count], 28)];
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 150;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BannerCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"BannerCell"];
    cell.scrollView.pagingEnabled = YES;
    [cell setCellValue:self.bannerList];
    cell.scrollView.contentSize = CGSizeMake(cell.scrollView.width*[self.bannerList count], cell.scrollView.height);
    cell.delegate = self;
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.finderList count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 190;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FiderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FiderListCell" forIndexPath:indexPath];
    [cell setCellValue:[self.finderList objectAtIndex:indexPath.row]];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FinderDetailViewController *detail = [[FinderDetailViewController alloc]init];
    FinderListModel *model = [self.finderList objectAtIndex:indexPath.row];
    detail.finderId = [NSString stringWithFormat:@"%.0f",model.internalBaseClassIdentifier];
    [self.rt_navigationController pushViewController:detail animated:YES complete:nil];
}
#pragma mark - bannerDelegate
-(void)bannerClicked:(BannerListModel *)model{
    FinderDetailViewController *detail = [[FinderDetailViewController alloc]init];
    detail.finderId = [NSString stringWithFormat:@"%.0f",model.internalBaseClassIdentifier];
    [self.rt_navigationController pushViewController:detail animated:YES complete:nil];
}
#pragma mark - instance
-(UIScrollView*)categoryList{
    if (!_categoryList) {
        _categoryList = [[UIScrollView alloc]init];
        _categoryList.backgroundColor = [UIColor clearColor];
        _categoryList.showsHorizontalScrollIndicator = NO;
    }
    return _categoryList;
}
-(UITableView*)mainTableView{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc]init];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.tableFooterView = [UIView new];
        [_mainTableView registerNib:[UINib nibWithNibName:@"FiderListCell" bundle:nil] forCellReuseIdentifier:@"FiderListCell"];
        [_mainTableView registerNib:[UINib nibWithNibName:@"BannerCell" bundle:nil] forHeaderFooterViewReuseIdentifier:@"BannerCell"];
        _mainTableView.showsVerticalScrollIndicator = NO;
    }
    return _mainTableView;
}
-(FinderViewModel*)finderViewModel{
    if (!_finderViewModel) {
        _finderViewModel = [[FinderViewModel alloc]init];
    }
    return _finderViewModel;
}
-(NSMutableArray*)catList{
    if (!_catList) {
        _catList = [[NSMutableArray alloc]init];
    }
    return _catList;
}
-(NSMutableArray*)finderList{
    if (!_finderList) {
        _finderList = [[NSMutableArray alloc]init];
    }
    return _finderList;
}
-(NSMutableArray*)bannerList{
    if (!_bannerList) {
        _bannerList = [[NSMutableArray alloc]init];
    }
    return _bannerList;
}
#pragma mark - UITextFiledDelegate
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.keyWord = textField.text;
    [self requestData];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
